package com.example.finalwork

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.example.finalwork.utils.SharedPreferencesManager
import com.example.finalwork.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private lateinit var sharedPreferencesManager: SharedPreferencesManager

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        sharedPreferencesManager = SharedPreferencesManager(this)

        // 获取用户名并设置显示
        val username = intent.getStringExtra("username")
        if (username == null) {
            binding.tvUsername.text = "您还未登录，右上角进入登录"
        }else{
            binding.tvUsername.text = "欢迎, $username"
        }


        // 检查是否已登录，如果未登录则隐藏井字棋按钮
        binding.btnToActivity1.visibility = if (username != null) View.VISIBLE else View.GONE

        binding.btnToActivity1.setOnClickListener {
            val intent = Intent(this, MainActivity1::class.java)
            startActivity(intent)
        }

        binding.toolbar.inflateMenu(R.menu.main_menu)
        binding.toolbar.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.action_logout -> {
                    // 清除 SharedPreferences 中的用户信息
                    sharedPreferencesManager.clearUser()
                    val intent = Intent(this, LoginActivity::class.java)
                    startActivity(intent)
                    finish()
                    true
                }
                else -> false
            }
        }
    }
}
